﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace _5E.Utils.ReflectionHelper
{
    /// <summary>
    /// 程序说明：动态属性存取缓存
    /// 创建作者：jeff_zhao
    /// 创建时间：2009-01-08
    /// </summary>
    public partial class DynamicPropertyAccessorCache
    {
        #region 变量

        /// <summary>
        /// 互斥体
        /// </summary>
        private object m_Mutex = new object();

        /// <summary>
        /// 缓存
        /// </summary>
        private IDictionary<Type, IDictionary<string, DynamicPropertyAccessor>> m_DicCache = new Dictionary<Type, IDictionary<string, DynamicPropertyAccessor>>();

        #endregion

        #region 实例方法

        public DynamicPropertyAccessor GetAccessor(PropertyInfo propertyInfo)
        {
            return this.GetAccessor(propertyInfo.ReflectedType, propertyInfo.Name);
        }

        public DynamicPropertyAccessor GetAccessor(Type type, string propertyName)
        {
            DynamicPropertyAccessor accessor;
            IDictionary<string, DynamicPropertyAccessor> dicTypeCache;

            if (this.m_DicCache.TryGetValue(type, out dicTypeCache))
            {
                if (dicTypeCache.TryGetValue(propertyName, out accessor))
                {
                    return accessor;
                }
            }

            lock (this.m_Mutex)
            {
                if (dicTypeCache == null)
                {
                    dicTypeCache = new Dictionary<string, DynamicPropertyAccessor>();
                    this.m_DicCache.Add(type, dicTypeCache);
                }

                accessor = new DynamicPropertyAccessor(type, propertyName);
                dicTypeCache.Add(propertyName, accessor);

                return accessor;
            }
        }

        #endregion
    }
}
